import { observable, action, computed, toJS } from "mobx";
import { getTopTabs, getInnerTabs, getRightMenus } from '../../apis/card';
import _ from 'lodash';
import { isNumber } from "../../util/typeUtil";
import window, { replaceE8Url } from '../../util';
import CardStore from '.';
import { message, Button } from 'antd';
import Search from '../list';
import { WeaLocaleProvider,WeaTools } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;
import $ from "jquery";
import {checkHref} from '../../util/typeUtil';
const Base64 = WeaTools.Base64;

let numval = 0;
let modeTitle = "";
export default class CardTab {
    card: CardStore;
    constructor(card: CardStore) {
        this.card = card;
        if(card&&card.cardTab){
            this.topTabs=card.cardTab.topTabs;
            this.innerTab=card.cardTab.innerTab;
        }
    }
    @observable rightMenus: any[] = [];
    @observable quickButton = {};
    @observable innerTab: any[] = [];
    @observable topTabs: any[] = [];
    @observable topActiveKey = '';
    @observable topDropActiveKey = '';
    @observable innerTabSelectedKey: string = '1000';
    @observable isCube: boolean = false;
    @observable hrefUrl: string = "";

    reloadModeDefaultParams: any = {};
    RightMenusData: any[] = [];
    urlMap: any = {};
    confirmMap:any ={};

    @observable disabled: boolean = false;

    init = (params: any) => {
        this.getRightMenus(params);
        if (!this.card.isInline) {
            this.getTopTabs(params);
            this.getInnerTabs(params);
        }
    }

    @computed
    get tabDatas(): any[] {
        if(numval == 0){
            modeTitle = this.card.base.modeTitle;
            if(modeTitle != undefined && modeTitle != ''){
                if (modeTitle.startsWith('base64_')) {
                    modeTitle = modeTitle.substring(7, modeTitle.length);
                    modeTitle = Base64.decode(modeTitle);
                }
                numval = 1;
            }
        }
        return this.innerTab && this.innerTab.slice().length > 0 ?
            [{ key: "1000", title: getLabel(1361,"基本信息")}, ...this.innerTab.slice()] :
            []
    }
    @computed
    get title(): string {
        numval = 0;
        if(numval == 0){
            modeTitle = this.card.base.modeTitle;
            if(modeTitle != undefined && modeTitle != ''){
                if (modeTitle.startsWith('base64_')) {
                    modeTitle = modeTitle.substring(7, modeTitle.length);
                    modeTitle = Base64.decode(modeTitle);
                }
                numval = 1;
            }
        }
        if(CardStore.isTitleChanged == '1'){
            return modeTitle
        }else{
            return ""
        };
    }
    @computed
    get rightMenusToShow(): any[] {
        if (this.card.isSearchShow) {
            return Search.rightMenus.map(m => ({
                key: m.key,
                content: m.name,
                icon: <i className={m.icon} />,
                quickButton: m.quickButton,
                disabled: this.disabled
            }));
        } else if (this.card.isCardShow) {
            return this.card.card.cardTab.rightMenus.map(m => ({
                ...m,
                disabled: this.card.card.cardTab.disabled
            }));
        } else if (this.innerTabSelectedKey == '1000') {
            return this.rightMenus.map(m => ({
                ...m,
                disabled: this.disabled
            }));;
        } else {
            return [];
        }
    }
    @computed
    get quickButtons(): any[] {
        const type = this.card.base.type;
        let buttons  : any = [
        ];
        if(type == '0'){
            const isallowlike = this.card.isallowlike;
            const likeshowname = this.card.likeshowname;
            const isallowdislike = this.card.isallowdislike;
            const dislikeshowname = this.card.dislikeshowname;
            const likecount = this.card.likecount;
            const dislikecount = this.card.dislikecount;
            let liketitle = likeshowname;
            let disliketitle = dislikeshowname;
            let likeicon = '';
            let dislikeicon = '';
            if(this.card.likestatus == '1'){
                if(likeshowname == ''){
                    liketitle = getLabel('32944','取消赞');
                }else{
                    liketitle = getLabel('31129','取消')+likeshowname;
                }
                if(dislikeshowname == ''){
                    disliketitle = getLabel('515888','踩');
                  }
                likeicon = 'icon-coms02-like'
                dislikeicon = 'icon-coms02-Negative-comment-o'
            }else if(this.card.likestatus == '2'){
                if(likeshowname == ''){
                    liketitle = getLabel('32942','赞');
                  }
                if(dislikeshowname == ''){
                    disliketitle = getLabel('515889','取消踩');
                }else{
                    disliketitle = getLabel('31129','取消')+dislikeshowname;
                }
                likeicon = 'icon-coms02-like-o'
                dislikeicon = 'icon-coms02-Negative-comment'
            }else{
                if(likeshowname == ''){
                    liketitle = getLabel('32942','赞');
                }
                if(dislikeshowname == ''){
                    disliketitle = getLabel('515888','踩');
                }
                likeicon = 'icon-coms02-like-o'
                dislikeicon = 'icon-coms02-Negative-comment-o'
            }

            if(isallowlike == '1'){
                buttons.push(
                    <div style={{'cursor': 'pointer'}}>
                        <i title={liketitle} className={likeicon} onClick={() => {this.likeOrDislike('1')}}/><span>{' '+likeshowname+' ('+likecount+')'}</span>
                    </div>
                )
            }
            if(isallowdislike == '1'){
                buttons.push(
                    <div style={{'cursor': 'pointer'}}>
                        <i title={disliketitle} className={dislikeicon} onClick={() => {this.likeOrDislike('2')}}/><span>{' '+dislikeshowname+' ('+dislikecount+')'}</span>
                    </div>
                )
            }

        }

        let quickRightMenus = this.rightMenusToShow ? this.rightMenusToShow.filter(d => d.quickButton) : [];
        if (quickRightMenus.length > 4) {
            quickRightMenus = quickRightMenus.slice(0, 4);
        }
         quickRightMenus.map((d) => (
                buttons.push(
                    <Button type="primary"
                    disabled={d.disabled}
                    onClick={() => {
                    this.rightMenuHandle(d.key);
                    }} >{d.content}
                   </Button>
                )
        ));
        return buttons;
    }
    likeOrDislike(key){
        if(key == '1'){
            if(this.card.likestatus == '1'){
                this.card.likeOrdislike('0');
            }else{
                this.card.likeOrdislike(key);
            }
        }else if(key == '2'){
            if(this.card.likestatus == '2'){
                this.card.likeOrdislike('0');
            }else{
                this.card.likeOrdislike(key);
            }
        }

    }
    rightMenuHandle = (key) => {
        if (this.card.isSearchShow) {
            Search.rightMenuClick(key);
        } else if (this.card.isCardShow) {
            this.card.card.Actions.runCustomAction(key);
        } else {
            this.card.Actions.runCustomAction(key);
        }
    }
    @action
    getTopTabs = (params: any) => {
        getTopTabs(params).then(({ status, errorCode, error, topTabs,defaultselect }: any) => {
            if (status == '1') {
                this.topTabs = this.createTopTab(topTabs);
                if(defaultselect&&defaultselect!=''){
                    //直接调用,内嵌tab页没时间加载,可能会变成空
                    setTimeout(()=>{this.changeTopActiveKey(defaultselect)},500);
                }
            } else {
                message.error(`[${getLabel(127353, "错误") + errorCode}]:${error}`);
            }
        })
    }

    createTopTab = (params: any) => {
        let cardTopTabs: any = [];
        _.each(params, (value: any) => {
            const key = value.detailid;
            if (key.indexOf("group") > -1) {
                cardTopTabs.push({
                    key: key,
                    title: value.groupname,
                    ...value,
                    groups: this.createTopTab(value.groups),
                })
            } else {
                cardTopTabs.push({
                    key: key,
                    title: value.expendname,
                    ...value
                })
            }
        });
        return cardTopTabs;
    }

    @action
    getInnerTabs = (params: any) => {
        let cardInnerTabs: any = [];
        getInnerTabs(params).then(({ status, errorCode, error, innerTabs, defaultselect}: any) => {
            if (status == '1') {
                _.each(innerTabs, (value: any) => {
                    cardInnerTabs.push({
                        key: value.detailid,
                        title: value.expendname,
                        ...value
                    })
                });
                this.innerTab = cardInnerTabs;
                if(defaultselect&&defaultselect!=''){
                    this.changeInnerTabSelectedKey(defaultselect)
                }
            } else {
                message.error(`[${getLabel(127353, "错误") + errorCode}]:${error}`);
            }
        })
    }

    @action
    getRightMenus = (params: any) => {
        getRightMenus(params).then(({ status, errorCode, error, rightMenus, urlMap,confirmMap={} }: any) => {
            if (status == '1') {
                this.initRightMenus(_.compact(rightMenus));
                this.urlMap = urlMap;
                this.confirmMap = confirmMap;
            } else {
                message.error(`[${getLabel(127353, "错误") + errorCode}]:${error}`);
            }
        })
    }
    @action
    setRightMenus = (rightmenus: any[]) => {
        this.rightMenus = rightmenus.map(rightMenu => {
            return {
                ...rightMenu,
                icon: <i className={rightMenu.icon} />
            }
        })
    }

    getRightMenu = (key: string): any => {
        const rightMenus = this.rightMenus.slice(0).filter(d => d.key == key);
        if (rightMenus.length > 0) {
            return rightMenus[0];
        }
        return {};
    }

    @action
    initRightMenus = (rightMenus) => {
        if (rightMenus) {
            this.rightMenus = rightMenus.map(rightMenu => (
                {
                    ...rightMenu,
                    content: rightMenu.name,
                    icon: <i className={rightMenu.icon} />,
                    quickButton: rightMenu.quickButton
                }
            ));
        } else {
            this.rightMenus = [];
        }
    }

    @action
    changeTopActiveKey = (key: string) => {
        if(Search && Search.slideModalVisible){//如果切换tab的时候有未关闭的Slider
            Search.showSlideModal(false, "", "");
        }
        let hreftarget: string = '';
        if (key == '0') {
            this.topActiveKey = key;
            this.topDropActiveKey = '';
            $("#tabcontentviewframe").hide().attr("src", "");
            this.isCube = false;
            if (this.innerTabSelectedKey) {
                this.changeInnerTabSelectedKey(this.innerTabSelectedKey)
            }
            return;
        }
        for (let i = 0; i < this.topTabs.length; i++) {
            let k = this.topTabs[i].key;
            if (isNumber(k)) {
                if (key == k) {
                    this.topActiveKey = key;
                    this.topDropActiveKey = '';
                    hreftarget = this.topTabs[i].hreftarget;
                    hreftarget = replaceE8Url(hreftarget);
                    this.hrefUrl = `${hreftarget}`;
                    if (hreftarget.indexOf("/spa/cube/index.html") >= 0||hreftarget.indexOf("/spa/cube/index.jsp") >= 0) {
                        this.isCube = true;
                        if (hreftarget.indexOf("main/cube/search") >= 0
                            || hreftarget.indexOf("main/cube/reply") >= 0 ||
                            hreftarget.indexOf("main/cube/viewCustomPage") >= 0) {
                            this.isCube = true;
                            $("#tabcontentviewframe").hide().attr("src", "");
                        } else {
                            this.isCube = false;
                            hreftarget = checkHref(hreftarget);
                            $("#tabcontentviewframe").attr("src", hreftarget).show();
                            $("#tabcontentviewframe")[0].contentWindow.location.href = hreftarget;

                        }
                    } else {
                        this.isCube = false;
                        $("#tabcontentviewframe").attr("src", hreftarget).show();
                        $("#tabcontentviewframe")[0].contentWindow.location.href = hreftarget;

                    }
                    return;
                }
            } else {  //下拉菜单切换
                let content = this.topTabs[i];
                for (let m = 0; m < content.groups.length; m++) {
                    let mk = content.groups[m].key;
                    if (key == mk) {
                        this.topActiveKey = k;
                        this.topDropActiveKey = mk;
                        hreftarget = content.groups[m].hreftarget;
                        hreftarget = replaceE8Url(hreftarget);
                        this.hrefUrl = `${hreftarget}`;
                        if (hreftarget.indexOf("/spa/cube/index.html") >= 0) {
                            this.isCube = true;
                            if (hreftarget.indexOf("main/cube/search") >= 0
                                || hreftarget.indexOf("main/cube/tree") >= 0 || hreftarget.indexOf("main/cube/reply") >= 0 ||
                                hreftarget.indexOf("main/cube/viewCustomPage") >= 0) {
                                this.isCube = true;
                                $("#tabcontentviewframe").hide().attr("src", "");
                            } else {
                                this.isCube = false;
                                $("#tabcontentviewframe").attr("src", hreftarget).show();
                                $("#tabcontentviewframe")[0].contentWindow.location.href = hreftarget;
                            }
                        } else {
                            this.isCube = false;
                            $("#tabcontentviewframe").attr("src", hreftarget).show();
                            $("#tabcontentviewframe")[0].contentWindow.location.href = hreftarget;
                        }
                        return;
                    }
                }
            }
        }
    }

    @action
    changeInnerTabSelectedKey = (key: string) => {
        if(Search && Search.slideModalVisible){//如果切换tab的时候有未关闭的Slider
            Search.showSlideModal(false, "", "");
        }
        this.innerTabSelectedKey = key;
        $("#tabcontentframe").hide().attr("src", '');
        $(".cube-card-iframe").hide();
        if (key == '1000') {
            this.card.isCardShow = false;
            this.card.isSearchShow = false;
            this.card.isShowReply = false;
            this.card.params['needdefaultselect']=0;
            this.card.reloadSearch(toJS(this.card.params));
            this.card.reply.initReply();
        } else {
            this.innerTab.slice().map(d => {
                if (d.detailid == key) {
                    let hreftarget = `${d.hreftarget}`;
                    if (hreftarget.indexOf('/main/cube/search') > -1) { //查询列表页面
                        this.card.isCardShow = false;
                        this.card.isShowReply = false;
                        this.card.isLogListShow  =false;
                        this.card.showSearch(hreftarget);
                    } else if (hreftarget.indexOf('/main/cube/card') > -1) {
                        this.card.isSearchShow = false;
                        this.card.isShowReply = false;
                        this.card.isLogListShow  =false;
                        this.card.showCard(hreftarget+"&isInnerCard=true"); //属于内嵌卡片在编辑保存的时候走自己的初始化请求，禁止页面跳转
                    } else if (hreftarget.indexOf('/main/cube/reply') > -1) {
                        this.card.isSearchShow = false;
                        this.card.isCardShow = false;
                        this.card.isLogListShow  =false;
                        this.card.showInnerReply(hreftarget);
                        this.card.reply.initReply();
                    }else if (hreftarget.indexOf('/main/cube/logList') > -1) {
                        this.card.isSearchShow = false;
                        this.card.isCardShow = false;
                        this.card.isShowReply = false;
                        this.card.showInnerLogList(hreftarget);
                    }  else {
                        hreftarget = checkHref(hreftarget);
                        this.card.isCardShow = false;
                        this.card.isSearchShow = false;
                        this.card.isShowReply = false;
                        this.card.isLogListShow  =false;
                        window.open(hreftarget, 'tabcontentframe');
                        $(".cube-card-iframe").show();
                        $("#tabcontentframe").attr("src", hreftarget).show();
                        $("#tabcontentframe")[0].contentWindow.location.href = hreftarget;
                    }
                }
            });
        }
    }

}
